package utility;

import java.nio.ByteBuffer;
import java.util.stream.IntStream;

public class Utility {
    public static String hex2string(byte[] data){
        return hex2string(data, 0, data.length);
    }

    public static String hex2string(byte[] data, int start, int len){
        StringBuilder str = new StringBuilder();
        IntStream.range(start, start + len)
                .mapToObj(i -> String.format("%02x", data[i]))
                .forEachOrdered(str::append);
        return str.toString();
    }
    public static byte[] string2hex(String str){
        assert str.length()%2==0;
        ByteBuffer buffer = ByteBuffer.allocate(Byte.BYTES * str.length() / 2);
        for(int i=0; i<str.length(); i+=2){
            String num = str.substring(i, i+2);
            int val = Integer.parseInt(num, 16);
            buffer.put((byte) val);
        }
        return buffer.array();
    }
}
